package org.flik.server;

import java.io.File;
import java.util.Date;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpSession;

import org.flik.server.bean.GenericBean;
import org.flik.server.dto.SessionInfo;
import org.flik.server.entity.FlikUser;

public class ServerUtils {
	public static final String LOGIN_INFO = "loginInfo";

	public static SessionInfo getSessionLoginInfo(HttpSession httpSession) {
		return (SessionInfo) httpSession.getAttribute(LOGIN_INFO);
	}

	public static FlikUser getLoggedInUser(HttpSession httpSession){
		Long loggedInUserId = getSessionLoginInfo(httpSession).getFlikUserId();
		GenericBean genericBean = ServerUtils.lookupBean(GenericBean.class);
		return genericBean.find(FlikUser.class, loggedInUserId);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T lookupBean(Class<T> clazz) {
		try {
			InitialContext ctx = new InitialContext();
			return (T) ctx.lookup("java:module/" + clazz.getSimpleName());
		} catch (NamingException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void redeployApplication(String applicationContext){
		String fileName = "C:/gwt/jboss-as-7.1.1.Final/standalone/deployments/" + applicationContext + ".war.deployed";
		File file = new File(fileName);
		file.setLastModified(new Date().getTime());		
	}
}
